package com.loansystem.config;

import com.loansystem.bean.user.User;
import com.loansystem.bean.user.User_Rule_VO;
import com.loansystem.service.user.impl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;
import java.util.Date;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserServiceImpl userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权方法");

        //创建一个简单的授权对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前用户 Subject 的信息
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
        User_Rule_VO roleName = userService.getRuleName(currentUser.getUser_mail());
        System.out.println(roleName.getAccess_name());
        //将权限字符添加到允许列表
        info.addStringPermission(roleName.getAccess_name());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证的方法");

        //调用数据库
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.getUserByUsername(token.getUsername());
        //如果用户
        if(user==null){
            return null;
        }
        //SimpleAuthenticationInfo(拿到当前用户信息,认证密码,"");
        return new SimpleAuthenticationInfo(user,user.getUser_pwd(),"");
    }
}
